"use strict";
const relies = ['js/vendor/requirejs/require.js', 'js/require.config.js']


document.title="武汉市农业地理信息服务平台"

String.prototype.trim = function() {
  return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

const addThisClass = (target) => {
  const navs = document.body.querySelectorAll(".layui-nav-child dd")
  navs.forEach((item, index)=>{
    if(item.id !=="exitBtn"){
      let i = item.querySelectorAll("a")[0].href.split("/").length
      let href  = item.querySelectorAll("a")[0].href.split("/")[i-1].split(".")[0]
      //console.log(href)
      if(target === href){
        item.setAttribute("class","layui-this")
      }
    }
  })
}

//定义添加方法，
// urls----script.src地址数组、callback---回调函数
const loadScripts = (urls, index, callback) => {
  callback = callback || function () { };
  //添加script属性，并添加到head中
  const loader = function (src, handler) {
    const script = document.createElement('script');
    //script.type = 'text/javascript';

    if(src==="js/vendor/requirejs/require.js"){
      script.setAttribute('data-main', `js/${index}.js`)
    }
    script.src = src;
    //重点！！！！script加载成功
    script.onload = function () {
      script.onload = null;
      script.onerror = null;
      handler();
    };
    script.onerror = function () {
      script.onload = null;
      script.onerror = null;
      callback({
        message: src + '依赖未加载成功！'
      });
    };
    //const head = document.getElementsByTagName('head')[0];
    (document.body).appendChild(script);
  };
  //自执行函数，用于循环loader
  (function run() {
    if (urls.length > 0) {
      loader(urls.shift(), run);
    } else {
      callback();
    }
  })();
  //console.log(document.head)
}



const addMianJs = (url, spare, )=>{
  const i = window.location.href.split("/").length - 1;
  const lastName = window.location.href.split("/")[i].split(".")[0];
  addThisClass(lastName)
  const request = new XMLHttpRequest();
  request.open("get", url);/*设置请求方法与路径*/
  request.send(null);/*不发送数据到服务器*/
  request.onload = () => {/*XHR对象获取到返回信息后执行*/
    if (request.status === 200) {/*返回状态为200，即为数据获取成功*/
      const json = JSON.parse(request.responseText);
      json.map((item, key)=>{
        if(lastName===item.pageName){
          loadScripts(relies, item.dataMain, (err) =>{
            if (err) {
              return console.log(err.message);
            }
          })
        } else if(!lastName){
          loadScripts(relies, spare, (err) =>{
            if (err) {
              return console.log(err.message);
            }
          })
        }
      })
    } else {
      console.log(request.status)
    }
  }
}

    addMianJs("./data/index.json", "index")
    // console.log(JSON.stringify(data))






